package cn.changeforyou.demo.netty.client;

import cn.changeforyou.demo.netty.common.Data;
import cn.changeforyou.demo.netty.common.Data.MsgType;
import cn.changeforyou.demo.netty.common.Req;
import cn.changeforyou.demo.netty.common.Req.ReqType;
import cn.changeforyou.demo.netty.common.Res;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhyu
 * @date 2020/9/9 11:10
 */
@Sharable
public class ClientHandler extends ChannelInboundHandlerAdapter {

    Logger log = LoggerFactory.getLogger(ClientHandler.class);
    String token;
    volatile String loginMsgId;
    volatile boolean loginSuccess;

    public ClientHandler(String token) {
        this.token = token;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Data data = (Data) msg;
        MsgType msgType = data.getMsgType();
        Object content = data.getContent();
        if (msgType == MsgType.response) {
            Res res = (Res) content;
            if(res.getMsgId().equals(loginMsgId)) {
                if(res.getCode() == 0) {
                    loginSuccess = true;
                    log.info("登录成功");
                }
            }
        }else if(msgType == MsgType.json) {
            // todo json业务处理代码
            log.info("收到推送信息: {}", content);
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Req req = new Req(token, ReqType.login);
        loginMsgId = req.getMsgId();
        ctx.writeAndFlush(Data.instanceReq(req));
        log.info("发起登录, 本地Ip:{}, token:{}", ((InetSocketAddress) ctx.channel().localAddress()).getAddress(), token);
    }

    /**
     * 处理断开重连
     */
    @SuppressWarnings("static-access")
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与服务器连接断开，尝试重新连接...");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

}
